var CryptoJS = require('crypto-js');

// AES解密工具
export function AES_Decrypt(data, secretKey) {
    if (!data || !secretKey) return;
    if (typeof data != 'string' || typeof secretKey != 'string') return;
    const key = CryptoJS.enc.Utf8.parse(secretKey);
    const bytes = CryptoJS.AES.decrypt(data, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    const outputStr = bytes.toString(CryptoJS.enc.Utf8);
    return outputStr;
}

export function parseTime(time, cFormat) {
    // 没有time或为null就返回
    if (arguments.length === 0 || !time) {
        return null;
    }
    const format = cFormat || '_{y}{m}{d}{h}{i}{s}';
    let date;
    if (typeof time === 'object') {
        date = time;
    } else {
        if (('' + time).length === 10) time = parseInt(time) * 1000;
        date = new Date(time);
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    };
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1];
        if (result.length > 0 && value < 10) {
            value = '0' + value;
        }
        return value || 0;
    });
    return time_str;
}

export function isExternal(path) {
    return /^(https?:|mailto:|tel:)/.test(path);
}

/**
 *
 * @param {*} tree 树形数组
 * @param {*} key children的属性,默认为children
 * @param {*} pid 为扁平化array添加上parentId的标记
 * @returns
 */
export function treeToList(tree, key = 'children', pid) {
    const cloneTree = cloneDeep(tree);
    var queen = [];
    var result = [];
    queen = queen.concat(cloneTree);
    while (queen.length) {
        var first = queen.shift();
        if (first[key]) {
            typeof pid !== 'undefined' &&
                first[key].forEach((item) => {
                    item.parentId = first[pid];
                });
            queen = queen.concat(first[key]);
            delete first[key];
        }

        result.push(first);
    }
    return result;
}

// 日期格式为 xxxx-xx-xx + 星期
export function dataFormat(longtime) {
    const add0 = function (m) {
        return m < 10 ? '0' + m : m;
    };
    const time = new Date(longtime);
    const y = time.getFullYear();
    const m = time.getMonth() + 1;
    const d = time.getDate();
    const h = time.getHours();
    const mm = time.getMinutes();
    const s = time.getSeconds();
    return {
        date: y + '-' + add0(m) + '-' + add0(d),
        week: getWeekDay(time)
    };
}

// 获取星期
function getWeekDay(longtime) {
    var week;
    const date = new Date(longtime);
    if (date.getDay() == 0) week = '周日';
    if (date.getDay() == 1) week = '周一';
    if (date.getDay() == 2) week = '周二';
    if (date.getDay() == 3) week = '周三';
    if (date.getDay() == 4) week = '周四';
    if (date.getDay() == 5) week = '周五';
    if (date.getDay() == 6) week = '周六';
    return week;
}

export function valueCheck(value, fix, none) {
    if (fix == undefined) {
        fix = 0;
    }
    if (none == undefined) {
        none = '-';
    }
    if (value == undefined) {
        // 过滤掉undefined 和 null
        return none;
    }
    if (value == 'NaN') {
        return none;
    }
    if (typeof value == 'string') {
        let temp = parseFloat(value);
        if (Number.isNaN(temp)) {
            return none;
        } else if (fix >= 0) {
            return temp.toFixed(fix);
        } else {
            return temp;
        }
    } else if (typeof value == 'number') {
        if (value == 0) {
            return none;
        }
        if (fix >= 0) {
            return value.toFixed(fix);
        } else {
            return value;
        }
    }
    return value;
}
/**
 * 计算数组的百分比
 * @param {*} dataList
 * @param {*} dataField
 * @param {*} needRound 是否需要取整
 */
export function calcListPercent(dataList, dataField, needRound) {
    if (!Array.isArray(dataList)) {
        return;
    }
    if (dataList.length == 0) {
        return;
    }
    if (dataField == undefined || typeof dataField != 'string') {
        dataField = 'count';
    }
    if (needRound == undefined) {
        needRound = true;
    }
    const firstItem = dataList[0];
    if (!firstItem.hasOwnProperty(dataField)) {
        return;
    }
    let totalCount = dataList.reduce((total, item) => {
        let targetValue = item[dataField];
        if (typeof targetValue == 'string') {
            targetValue = parseFloat(targetValue);
        }
        total += targetValue;
        return total;
    }, 0);
    if (totalCount == 0) {
        dataList.forEach((item) => {
            item.percent = 0;
        });
        return;
    }
    let roundFix = 0;
    for (let i = 0; i < dataList.length; ++i) {
        let dataItem = dataList[i];
        let targetValue = dataItem[dataField];
        if (typeof targetValue == 'string') {
            targetValue = parseFloat(targetValue);
        }
        let percentTmp = (targetValue * 100) / totalCount;
        let percent = 0;
        if (needRound) {
            if (i == dataList.length - 1) {
                percent = Math.round(percentTmp - roundFix);
            } else {
                percent = Math.round(percentTmp);
                roundFix += percent - percentTmp;
            }
            dataItem.percent = percent;
        } else {
            dataItem.percent = percentTmp;
        }
    }
}

/**
 * 深拷贝一个对象或者数组(忽略值为function、undefied以及Symbol的字段，对date类型的支持不友好)
 * @param {json} object
 */
export function deepCopy(object) {
    if (typeof object != 'object') {
        return {};
    }
    let objStr = JSON.stringify(object);
    return JSON.parse(objStr);
}

/**
 * 深拷贝一个对象或者数组
 * @param {json} object
 */
export function cloneDeep(target) {
    if (typeof target == 'object' && target != null) {
        let result = Array.isArray(target) ? [] : {};
        for (let item in target) {
            if (typeof target[item] == 'object' && target[item] != null) {
                result[item] = deepCopy(target[item]);
            } else {
                result[item] = target[item];
            }
        }
        return result;
    } else {
        return target;
    }
}
